#!/usr/bin/env python
# -*- coding: utf-8 -*-

import asyncio
from typing import List, Dict, Any, Optional

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.exc import IntegrityError

from app.core.logging import get_logger
from app.core.utils import generate_uuid
from app.models.database import Project
from app.repositories.mysql import init_db, get_db_session

# 创建日志记录器
logger = get_logger("db_init")


async def create_default_project() -> None:
    """创建默认项目"""
    async for session in get_db_session():
        # 检查是否已存在默认项目
        result = await session.execute(select(Project).filter(Project.name == "默认项目"))
        default_project = result.scalars().first()
        
        if default_project:
            logger.info("默认项目已存在，无需创建")
            return
        
        # 创建默认项目
        default_project = Project(
            id=generate_uuid(),
            name="默认项目",
            description="系统默认项目，用于测试和演示"
        )
        
        try:
            session.add(default_project)
            await session.commit()
            logger.info(f"已创建默认项目，ID: {default_project.id}")
        except IntegrityError:
            await session.rollback()
            logger.warning("创建默认项目时发生冲突，可能已被其他进程创建")
        except Exception as e:
            await session.rollback()
            logger.error(f"创建默认项目失败: {str(e)}")


async def initialize_database() -> None:
    """初始化数据库"""
    try:
        # 创建表
        await init_db()
        
        # 创建默认项目
        await create_default_project()
        
        logger.info("数据库初始化完成")
    except Exception as e:
        logger.error(f"数据库初始化失败: {str(e)}")
        raise